package com.tj.shopping.web.controller;

import com.tj.shopping.entity.User;
import com.tj.shopping.enums.ResultEnum;
import com.tj.shopping.service.IUserService;
import com.tj.shopping.service.impl.UserServiceImpl;
import com.tj.shopping.util.EmailUtil;
import com.tj.shopping.util.FileUploadUtil;
import com.tj.shopping.util.StringUtils;
import com.tj.shopping.util.ValidateCodeUtils;
import com.tj.shopping.vo.ResultVO;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user")
public class UserController extends BaseController {
    IUserService service = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String op = req.getParameter("op");
        if ("login".equals(op)) {
            doLogin(req, resp);
        } else if ("reg".equals(op)) {
            doReg(req, resp);
        } else if ("check".equals(op)) {
            doCheck(req, resp);
        }if("findall".equals(op)){
            doFindall(req,resp);
        }else if ("update".equals(op)){
            doUpdate(req,resp);
        }else if ("finds".equals(op)) {
            doFinds(req, resp);
        }else if ("exit".equals(op)) {
            doExit(req, resp);
        }else if ("sendMsg".equals(op)) {
            doSendMsg(req, resp);
        } else {

        }
    }

    protected void doSendMsg(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        System.out.println("qq验证码");
        //获取邮箱
        String uemail = req.getParameter("uemail");
        if(!StringUtils.isNull(uemail)){
            //生成随机的6位验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            Map<String,Object> map = new HashMap<>();
            map.put("code", code);
            //调用自己封装的qq邮箱发送器发送邮箱
            EmailUtil.sendAuthCodeEmail(uemail,code);

            //需要将验证码保存到session中
            req.getSession().setAttribute(uemail, code);
//            req.getSession().setMaxInactiveInterval(60);//设置session有效期 60秒,这里以后可能会用redis,所以先不设置！
            printToJson(resp,1);
        }else{
            printToJson(resp,0);
        }

    }
    protected void doReg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取验证码
        String code = req.getParameter("code");
        String email = req.getParameter("uemail");
        if (code != null){
            System.out.println(code);
            System.out.println(req.getSession().getAttribute(email));
            if (code.equals(req.getSession().getAttribute(email))){

                User user = parseRequest(req, User.class);
                System.out.println(user);
                int result = service.add(user);
                printToJson(resp, result);//1
            }else{
                printToJson(resp,2);
            }
        }else{
            printToJson(resp,0);
        }

    }

    protected void doExit(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        req.getSession().invalidate();
        // 设置响应头，告知前端注销成功
        printToJson(resp, 0);


    }
    private void doFinds(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String,Object> map = parseRequest(req);
        Map<String,Object> m = service.finds(map);
        printToJson(resp,m);//响应给页面的是m
    }

    private void doFindall(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String,Object> m = service.findall();
        printToJson(resp,m);//响应给页面的是m
    }


    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = parseRequest(req,User.class);
        String ustate = req.getParameter("ustate");
        if (ustate!=null){
            user.setUstate(Integer.parseInt(ustate));
        }

        System.out.println(user);
        int result = service.update(user);
        // 响应结果给页面
        printToJson(resp, result);

    }
    /**
     * 检查用户是否登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void doCheck(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            //说明未登录
            ResultVO vo = new ResultVO(ResultEnum.LOGIN_ERROR);
            printToJson(resp, vo);
            return;
        }
        Integer count = (Integer) req.getServletContext().getAttribute("count");
        //如果登录，返回用户数据和访问量给前端
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        ResultVO vo = new ResultVO(ResultEnum.SUCCESS, map);
        printToJson(resp, vo);
    }

    protected void doLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = parseRequest(req, User.class);
        User user2 = service.login(user.getUname(), user.getUpwd());
        if (null == user2) {
            printToJson(resp, 0);
            return;
        }else if (user2.getUstate().equals("0")){
            printToJson(resp, 5);
        }
        //登录成功
        ServletContext context = req.getServletContext();
        //设置session
        req.getSession().setAttribute("user", user2);

        printToJson(resp, user2);

    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
